package com.lg.atp.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.lg.atp.common.Constants;
import com.lg.atp.entity.TblAttachment;
import com.lg.atp.sercurity.SecurityUserHolder;
import com.lg.atp.service.IAttachmentService;

@RestController
@RequestMapping("file")
public class FileController {

	private static final Log log = LogFactory.getLog(FileController.class);
	
	
	private @Value("${targetFilePath}") String targetFilePath;
	
	
	@Autowired
	private IAttachmentService iAttachmentService;
	
	  @RequestMapping(value="uploadFile",method=RequestMethod.POST)
	  public Map<String, Object> fileUpload(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request){  
		 
		    Map<String,Object> result = new HashMap<String,Object>();
		    result.put("status", Constants.RETURN_SUCCESS);
		    InputStream is = null;
		    try{
		        // 判断文件是否存在  
		        if (!file.isEmpty()) {  
		            String fileName = file.getOriginalFilename();  
		            String fileType = "";
		            String newFileName = "";
		            String oldFileNameWithNoType = fileName;
		            Integer fileTypeIndex = fileName.lastIndexOf(".");
		            if(fileTypeIndex > 0){
		            	fileType = fileName.substring(fileTypeIndex+1,fileName.length());
		            	oldFileNameWithNoType = fileName.substring(0,fileTypeIndex);
		            }
		            	
		            is = file.getInputStream();
		            
		            //校验文件后缀是否被改动过
		           // result = checkFile(is);
		            //if(result.get("status").toString().equals(Constants.RETURN_FAIL))
		            	//return result;
		            //fileType = result.get("realFileType") == null?fileType:result.get("realFileType").toString();
		            if(StringUtils.isBlank(fileType))
		            	newFileName = oldFileNameWithNoType+"_"+new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
		            else
		                newFileName = oldFileNameWithNoType+"_"+new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+"."+fileType;
		            
		            
		            String toFilePath = targetFilePath+newFileName;
		            //上传FTP
		            FileUtils.copyInputStreamToFile(is, new File(toFilePath));
		            TblAttachment att = new TblAttachment();
		            att.setCreateUserId(SecurityUserHolder.getCurrentUser().getId());
		            att.setFileNameNew(newFileName);
		            att.setFileNameOld(fileName);
		            att.setFilePath(toFilePath);
		            att.setFileType(fileType);
		            att =  iAttachmentService.saveFile(att);
		            result.put("data", att);
		        } else{
		        	result.put("status", Constants.RETURN_FAIL);
		        	log.error("文件不存在");
		        	result.put("errorMessage", "文件不存在");
		        	return result;
		        }
		      
		    }catch(Exception e){
		    	e.printStackTrace();
		    	log.error("上传文件失败",e);
		    	result.put("errorMessage", "上传文件失败");
		    	result.put("status", Constants.RETURN_FAIL);
		    	return result;
		    }finally{
		    	if(is != null)
					try {
						is.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
		    }
		    
		    return result;
	    }
	
	
	/* private Map<String,Object> checkFile(InputStream is) throws Exception{
		 Map<String,Object> result = new HashMap<String,Object>();
		 result.put("status", Constants.RETURN_SUCCESS);
		//校验类型
         if(StringUtils.isNotBlank(allowFileTypes)){
         	String fileRealType = FileTypeUtils.getFileByFile(is);
         	if(StringUtils.isBlank(fileRealType)){
	            	result.put("status", Constants.RETURN_FAIL);
	            	result.put("errorMessage", "文件类型不对，请选择【"+allowFileTypes+"】中的类型进行上传");
	            	return result;
	            	
	            }
         	String[] fts = allowFileTypes.split(",");
         	boolean checked = false;
         	for(String ft:fts){
         		if(ft.toLowerCase().equals(fileRealType)){
         			checked = true;
         			break;
         		}
         	}
         	
         	if(!checked){
         		result.put("status", Constants.RETURN_FAIL);
	            	result.put("errorMessage", "文件类型不对，请选择【"+allowFileTypes+"】中的类型进行上传");
	            	return result;
         	}
         	result.put("realFileType", fileRealType);
         }
		 return result;
	 }*/
}
